<?php
/**
 * Created By PhpStorm
 * Author: patrick wu
 * Date: 2021/1/9
 * Time: 10:43
 */
namespace App\Service\Admin;

use App\Http\Model\Mysql\BoxSystemModel;
use Illuminate\Support\Facades\Hash;

class ManagerService extends BaseService
{
    /**
     * 系统管理员列表
     * @param int|null $limit
     * @param int $page
     * @return array
     */
    public function managerList(int $limit = null, int $page = 1)
    {
        $limit  =   empty($limit) ? self::PAGE_LIMIT : $limit;
        $model  =   BoxSystemModel::query();
        $count  =   $model->count();
        $list   =   $model->offset(($page - 1) * $limit)->limit($limit)->select(['id', 'account', 'nick_name'])
                    ->get()->each(function (&$item) {
                    });

        if ($list->isEmpty()) {
            return [true, []];
        } else {
            return [true, [
                'count' =>  $count,
                'list'  =>  $list->toArray(),
                'pages' =>  ceil($count / $limit),
                'current'=> $page
            ]];
        }
    }
    /**
     * 系统管理员添加
     * @param string $account
     * @param string $nick_name
     * @param string $password
     * @return array
     */
    public function managerAdd(string $account, string $nick_name, string $password)
    {
        if (BoxSystemModel::where(['account' => $account])->exists()) {
            return [false, '用户已存在'];
        }

        $result =   BoxSystemModel::create([
            'account'   =>  $account,
            'nick_name' =>  $nick_name,
            'password'  =>  Hash::make($password)
        ]);

        if ($result) {
            return [true, '添加成功'];
        } else {
            return [false, '添加失败'];
        }
    }

    /**
     * 系统管理员删除
     * @param int $manager_id
     * @return array
     */
    public function managerDelete(int $manager_id)
    {
        $account    =   BoxSystemModel::where(['id' => $manager_id])->value('account');
        if ($account == 'admin' || $manager_id == 1) {
            return [false, '系统用户不允许删除'];
        }

        $result =   BoxSystemModel::where(['id' => $manager_id])->delete();
        if ($result) {
            return [true, '删除成功'];
        } else {
            return [false, '删除失败'];
        }
    }

    /**
     * 系统管理员修改密码
     * @param int $manager_id
     * @param string $old_password
     * @param string $new_password
     * @return array
     */
    public function managerPassword(int $manager_id, string $old_password, string $new_password)
    {
        $password    =   BoxSystemModel::where(['id' => $manager_id])->value('password');

        if (!Hash::check($old_password, $password)) {
            return [false, '旧密码错误'];
        }

        $result     =   BoxSystemModel::where(['id' => $manager_id])->update([
            'password'  =>  Hash::make($new_password)
        ]);

        if ($result) {
            return [true, '修改成功'];
        } else {
            return [false, '修改失败'];
        }
    }
}
